<template>
  <basic-container>
    <avue-crud ref="crud"
               :option="option"
               :page.sync="page"
               :data="data"
               :table-loading="loading"
               :before-open="beforeOpen"
               v-model="form"
               @on-load="onload"
               @search-change="searchChange"
               @size-change="sizeChange"
               @current-change="currentChange"
               @refresh-change="refreshChange"
               @row-save="add"
               @row-update="update"
               @row-del="rowDel"

    >
<!--      <template slot="fileForm" slot-scope="{ row }">
        <el-upload
          v-model="form"
          action="#"
          ref="upload"
          multiple
          list-type="picture-card"
          :auto-upload="false"
          :on-change="elChange"
          :file-list="fileList"
          :upload-before="uploadBefore"
        >
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{ file }">
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.url"
              alt=""
            />
          </div>
        </el-upload>
      </template>-->
<!--      <template slot="fileForm">
          <avue-form
            :option="fileOption"
            v-model="form"
            :upload-before="uploadBefore"
            :upload-error="uploadError">
          </avue-form>
      </template>-->
<!--        <template slot="fileForm">
          <el-upload
            action="#"
            :auto-upload="false"
            accept='application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            :multiple="false"
            :on-exceed="() => this.$message.warning('只能选择一个文件')"
            :on-change="(file)=>{this.uploadFile=file}"
            :limit="1">
            <el-button
              slot="trigger"
              type="primary">选取文件
            </el-button>
            <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件，且不超过100Mb</div>
          </el-upload>
        </template>-->
      <template slot="fileForm">
        <el-upload
          action="#"
          :auto-upload="false"
          :multiple="false"
          :on-remove="fileOnRemove"
          :on-change="fileOnChange"
          :on-preview="fileOnPreview"
          :show-file-list="this.fileData.showFileList"
          :file-list="this.fileData.fileList"
          >
          <el-button slot="trigger" type="primary">选择文件</el-button>
          <div slot="tip" class="el-upload__tip">只能上传apk文件，且不超过100Mb</div>
        </el-upload>
      </template>

      <template slot="appStatus" slot-scope="scope" >
        <el-switch
          :active-value="1"
          :inactive-value="0"
          v-model="scope.row.appStatus"
          @change="changeStatus(scope.row)" >
        </el-switch>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {mapGetters} from "vuex";
import {tableOption} from '@/const/crud/admin/app';
import {create, modify, delObj, queryPage ,putStatus} from "@/api/sys/app";

export default {
  data(){
    return {
      form: {},
      fileData:{
        fileList:[],
        showFileList: false,
        enableDownload: false
      },
      dictData:{
        appType:[]
      },
      option: tableOption,
      loading: false,
      data: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 5, // 每页显示多少条,
        pageSizes: [ 5, 10, 20, 30, 50],
        isAsc: false //是否倒序
      }
    }
  },
  computed: {
    ...mapGetters(["permissions"])
  },
  created() {
    this.sys_app_add = this.permissions["sys_app_add"];
    this.sys_app_edit = this.permissions["sys_app_edit"];
    this.sys_app_del = this.permissions["sys_app_del"];
  },
  methods:{
    onload(page) {
      this.loading = true;
      queryPage(Object.assign({
        currentPage: page.currentPage,
        pageSize: page.pageSize
      }, this.searchForm)).then(response => {
        this.data = response.data.data.list;
        this.page.total = parseInt(response.data.data.total);
        this.loading = false;
      });
    },
    searchChange(form, done) {
      this.page.currentPage = 1
      this.searchForm = form;
      this.onload(this.page);
      done()
    },
    refreshChange() {
      this.onload(this.page)
    },
    sizeChange(pageSize) {
      this.page.currentPage = 1
      this.page.pageSize = pageSize
    },
    currentChange(current) {
      this.page.currentPage = current
    },
    add(row, done, loading) {
      if(this.fileData.fileList.length === 0 ){
        this.$message.warning("请选择软件包");
        // 取消禁用不关闭弹框（avue-crud加入了防重提交机制，禁用按钮的loading状态）
        this.$refs.crud.$refs.dialogForm.$refs.tableForm.allDisabled = false
        return ;
      }
      //表单提交
      let param = new FormData();
      //将文件append到formData对象
      param.append("file", this.fileData.fileList[0].raw);
      //其他表单属性append
      param.append("appCode",this.form.appCode);
      param.append("appName",this.form.appName);
      param.append("appType",this.form.appType);
      param.append("appVersion",this.form.appVersion);
      create(param).then(() => {
        this.onload(this.page);
        done();
        this.$notify.success('创建成功')
      }).catch(() => {
        loading();
      });
    },
    update(row, done, loading) {
      //表单提交
      let param = new FormData();
      if(this.fileData.fileList.length > 0 ){
        //将文件append到formData对象
        param.append("file", this.fileData.fileList[0].raw);
      }
      //其他表单属性append
      param.append("id",row.id);
      param.append("appName",this.form.appName);
      param.append("appVersion",this.form.appVersion);
      modify(param).then(() => {
        this.onload(this.page);
        done();
        this.$notify.success('修改成功')
      }).catch(() => {
        loading();
      });
    },
    rowDel(row, index) {
      if(row.appStatus === 1 ){
        this.$message.warning("APP已上线不能删除");
        return ;
      }
      const _this = this
      this.$confirm('是否确认删除ID为' + row.id, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delObj(row)
      }).then(data => {
        _this.$message.success('删除成功')
        this.onload(this.page)
      })
    },
    changeStatus(row){
      putStatus(row).then((res)=>{
        console.log("changeStatus res:{}",res)
        this.$message.success('操作成功');
      });
    },
    fileOnRemove(){
      this.fileData.fileList = [];
      this.fileData.showFileList = false;
      this.fileData.enableDownload = false;
    },
    fileOnChange(file){
      if(this.form.appType === undefined || this.form.appType === ''){
        this.$message.warning('请先选择app类型');
        return false;
      }
      const sizeLimit = file.size / 1024 / 1024 > 100
      if (sizeLimit) {
        this.$message.warning('上传文件大小不能超过 100MB!')
        return false;
      }
      const fileFamart = file.name.split('.')[file.name.split('.').length - 1];
      if (fileFamart !== 'apk' && this.form.appType === 0) {
        this.$message.warning('必须上传apk格式的文件!')
        return false;
      }
      this.fileData.fileList = [];
      this.fileData.fileList.push(file);
      this.fileData.showFileList = true;
      this.fileData.enableDownload = false;
      return true;
    },
    fileOnPreview(file){
      if(this.fileData.enableDownload){
        const a = document.createElement('a');
        const event = new MouseEvent('click');
        a.href = file.url;
        a.dispatchEvent(event);
      }
    },
    beforeOpen(done,type){
      if(['add'].includes(type)){}
      if(['view'].includes(type)){}
      // 如果类型是编辑
      if(['edit'].includes(type)){
        if(this.form.appStatus === 1){
          this.$message.warning("APP已上线不能修改");
          return ;
        }
        this.fileData.fileList=[]
        this.fileData.fileList.push({
          name: this.form.attName,
          url: this.form.attUrl
        });
        this.fileData.showFileList = true;
        this.fileData.enableDownload = true;
        console.log("this.fileData.fileList:{}",this.fileData.fileList);
      }
      done();
    }
  }
}
</script>
